package com.ugoodtech.mdcc.client.service.impl;

        /* Copyright (C) Ugoodtech, Inc - All Rights Reserved.
         * Unauthorized copying of this file, via any medium is strictly prohibited.
         * Proprietary and confidential.
         * Written by Stone Shaw.
         */


import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.Brand;
import com.ugoodtech.mdcc.core.domain.Department;
import com.ugoodtech.mdcc.core.domain.Gender;
import com.ugoodtech.mdcc.core.domain.ModuleAuthority;
import com.ugoodtech.mdcc.core.domain.Nation;
import com.ugoodtech.mdcc.core.domain.QUserProfile;
import com.ugoodtech.mdcc.core.domain.Station;
import com.ugoodtech.mdcc.core.domain.User;
import com.ugoodtech.mdcc.core.domain.UserProfile;
import com.ugoodtech.mdcc.core.domain.UserType;
import com.ugoodtech.mdcc.core.exception.UsernameAlreadyExistException;
import com.ugoodtech.mdcc.core.exception.VStarException;
import com.ugoodtech.mdcc.core.repository.DepartmentRepository;
import com.ugoodtech.mdcc.core.repository.UserProfileRepository;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.UserProfileService;
import com.ugoodtech.mdcc.client.service.UserService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.transaction.Transactional;

import io.swagger.annotations.ApiParam;

@Service
public class UserProfileServiceImpl implements UserProfileService {
    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private UserService userService;


    private static final Logger logger = LoggerFactory.getLogger(UserProfileServiceImpl.class);

    @Override
    public Page<UserProfile> querySystemUser(@ApiParam("类型") @RequestParam(value = "userType", required = false) String userType,
                                             @ApiParam("员工编号") @RequestParam(value = "code", required = false) String code,
                                             @ApiParam("姓名") @RequestParam(value = "name", required = false) String name,
                                             @ApiParam("手机号码") @RequestParam(value = "telephone", required = false) String telephone,
                                             @ApiParam("关联部门") @RequestParam(value = "departmentIds", required = false) Long departmentIds, Pageable pageable) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.deleted.eq(false));
        builder.and(qUserProfile.user.userType.ne(UserType.customer));
        if (!StringUtils.isEmpty(code)) {
            builder.and(qUserProfile.serialNumber.like("%" + code + "%"));
        }
        if (!StringUtils.isEmpty(name)) {
            builder.and(qUserProfile.realName.like("%" + name + "%"));
        }
        if (StringUtils.isNotEmpty(telephone)) {
            builder.and(qUserProfile.telephone.like("%" + telephone + "%"));
        }
        if (null != departmentIds && departmentIds != 0) {
            builder.and(qUserProfile.departmentList.any().id.eq(departmentIds));
        }
        Sort sort = new Sort(Sort.Direction.DESC, "creationTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<UserProfile> userProfiles = userProfileRepository.findAll(builder, pageable);
        return userProfiles;
    }

    @Override
    public JsonResponse userInfoExport(@ApiParam("员工编号") @RequestParam(value = "code", required = false) String code,
                                       @ApiParam("姓名") @RequestParam(value = "name", required = false) String name,
                                       @ApiParam("手机号码") @RequestParam(value = "telephone", required = false) String telephone,
                                       @ApiParam("关联部门") @RequestParam(value = "departmentIds", required = false) Long departmentIds) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
//        builder.and(qUserProfile.deleted.eq(false));
        builder.and(qUserProfile.user.userType.ne(UserType.customer));
        if (!StringUtils.isEmpty(code)) {
            builder.and(qUserProfile.serialNumber.like("%" + code + "%"));
        }
        if (!StringUtils.isEmpty(name)) {
            builder.and(qUserProfile.realName.like("%" + name + "%"));
        }
        if (StringUtils.isNotEmpty(telephone)) {
            builder.and(qUserProfile.telephone.like("%" + telephone + "%"));
        }
        if (null != departmentIds && departmentIds != 0) {
            builder.and(qUserProfile.departmentList.any().id.eq(departmentIds));
        }
        Sort sort = new Sort(Sort.Direction.DESC, "creationTime");
        Pageable pageable = new PageRequest(0, 500, sort);
        Page<UserProfile> userProfileList = userProfileRepository.findAll(builder, pageable);
//        List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(builder);
        List<String[]> userInfoList = getUserInfoExport(userProfileList.getContent());
//        List<String[]> userInfoList = getUserInfoExport(userProfileList);
        return JsonResponse.successResponseWithData(userInfoList);
    }

    private List<String[]> getUserInfoExport(List<UserProfile> userProfileList) {
        List<String[]> userInfoList = new ArrayList<>();
        for (UserProfile userProfile : userProfileList) {
            String[] strings = new String[11];
            if (userProfile != null) {
                //获取编号
                if (StringUtils.isNotEmpty(userProfile.getSerialNumber())) {
                    strings[0] = userProfile.getSerialNumber();
                } else {
                    strings[0] = "";
                }
                //获取姓名
                if (StringUtils.isNotEmpty(userProfile.getRealName())) {
                    strings[1] = userProfile.getRealName();
                } else {
                    strings[1] = "";
                }
                //获取手机号
                if (StringUtils.isNotEmpty(userProfile.getTelephone())) {
                    strings[2] = userProfile.getTelephone();
                } else {
                    strings[2] = "";
                }
                //设置部门类型
                String departmentStr = getDepartmentStr(userProfile);
                strings[3] = getDepartmentType(departmentStr);
                //所属部门
                strings[4] = departmentStr;
                //所属省份
                strings[5] = getNationStr(userProfile);
                //汽车品牌
                strings[6] = getBrandStr(userProfile);
                //选择的维修站
                strings[7] = getStationStr(userProfile);
                //品牌定位
                if (StringUtils.isNotEmpty(userProfile.getProincesAndBrands())) {
                    strings[8] = userProfile.getProincesAndBrands();
                } else {
                    strings[8] = "";
                }
                //功能权限
                strings[9] = getModuleAuthorityStr(userProfile);
                //状态
                strings[10] = getUserStatStr(userProfile);
            } else {
                logger.info("有用户没有数据ID为");
                continue;
            }
            userInfoList.add(strings);
        }
        return userInfoList;
    }

    private String getDepartmentStr(UserProfile userProfile) {
        StringBuffer stringBuffer = new StringBuffer("");
        List<Department> departmentList = userProfile.getDepartmentList();
        if (departmentList != null && departmentList.size() > 0) {
            for (Department department : departmentList) {
                if (StringUtils.isNotEmpty(department.getTotalName())) {
                    stringBuffer.append(department.getTotalName() + ",");
                }
            }
        }
        return stringBuffer.toString();
    }

    private String getNationStr(UserProfile userProfile) {
        StringBuffer stringBuffer = new StringBuffer("");
        List<Nation> nationList = userProfile.getNationList();
        if (nationList != null && nationList.size() > 0) {
            for (Nation nation : nationList) {
                if (StringUtils.isNotEmpty(nation.getProvince())) {
                    stringBuffer.append(nation.getProvince() + ",");
                }
            }
        }
        return stringBuffer.toString();
    }

    private String getBrandStr(UserProfile userProfile) {
        StringBuffer stringBuffer = new StringBuffer("");
        List<Brand> brandList = userProfile.getBrandList();
        if (brandList != null && brandList.size() > 0) {
            for (Brand brand : brandList) {
                if (StringUtils.isNotEmpty(brand.getBrandName())) {
                    stringBuffer.append(brand.getBrandName() + ",");
                }
            }
        }
        return stringBuffer.toString();
    }

    private String getStationStr(UserProfile userProfile) {
        StringBuffer stringBuffer = new StringBuffer("");
        List<Station> stationList = userProfile.getStationList();
        if (stationList != null && stationList.size() > 0) {
            for (Station station : stationList) {
                if (StringUtils.isNotEmpty(station.getName())) {
                    stringBuffer.append(station.getName() + ",");
                }
            }
        }
        return stringBuffer.toString();
    }

    private String getModuleAuthorityStr(UserProfile userProfile) {
        StringBuffer stringBuffer = new StringBuffer("");
        User user = userProfile.getUser();
        if (user != null && user.getAuthorities() != null && user.getAuthorities().size() > 0) {
            Set<ModuleAuthority> authorities = user.getAuthorities();
            for (ModuleAuthority authority : authorities) {
                if (authority != null && StringUtils.isNotEmpty(authority.getDescription())) {
                    stringBuffer.append(authority.getDescription() + ",");
                }
            }
        }
        return stringBuffer.toString();
    }

    private String getUserStatStr(UserProfile userProfile) {
        if (userProfile.isEnabled()) {
            return "正常";
        } else {
            return "冻结";
        }
    }

    private String getDepartmentType(String departments) {
        String[] departmentArray = departments.split(",");
        for (String str : departmentArray) {
            if (StringUtils.isNotEmpty(str)) {
                if (str.indexOf("经销商") != -1) {
                    return "经销商";
                }
            }
        }
        return "其他部门";
    }


    @Override
    public Page<UserProfile> queryAadminSystemUser(@ApiParam("类型") @RequestParam(value = "userType", required = false) String userType,
                                                   @ApiParam("员工编号") @RequestParam(value = "code", required = false) String code,
                                                   @ApiParam("姓名") @RequestParam(value = "name", required = false) String name,
                                                   @ApiParam("手机号码") @RequestParam(value = "telephone", required = false) String telephone,
                                                   @ApiParam("关联部门") @RequestParam(value = "departmentIds", required = false) Long[] departmentIds, Pageable pageable) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.user.userType.eq(UserType.admin));
        if (!StringUtils.isEmpty(userType)) {
            builder.and(qUserProfile.user.userType.eq(UserType.valueOf(userType)));
        }
        if (!StringUtils.isEmpty(code)) {
            builder.and(qUserProfile.serialNumber.like("%" + code + "%"));
        }
        if (!StringUtils.isEmpty(name)) {
            builder.and(qUserProfile.realName.like("%" + name + "%"));
        }
        if (StringUtils.isNotEmpty(telephone)) {
            builder.and(qUserProfile.telephone.eq(telephone));
        }
        if (null != departmentIds && departmentIds.length > 0) {
            builder.and(qUserProfile.department.id.in(departmentIds));
        }
        Sort sort = new Sort(Sort.Direction.DESC, "creationTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<UserProfile> userProfiles = userProfileRepository.findAll(builder, pageable);
        return userProfiles;
    }

    @Override
    public UserProfile queryOneUserProfile(String userNo, String name) throws VStarException {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        if (!StringUtils.isEmpty(userNo)) {
            builder.and(qUserProfile.serialNumber.eq(userNo));
        }
        if (!StringUtils.isEmpty(name)) {
            builder.and(qUserProfile.realName.eq(name));
        }
        Page<UserProfile> userProfiles = userProfileRepository.findAll(builder, new PageRequest(0, 1));
        if (userProfiles.getTotalElements() > 1) {
            throw new VStarException("用户存在多个");
        } else if (userProfiles.getTotalElements() == 1) {
            return userProfiles.getContent().get(0);
        } else {
            throw new VStarException("没有用户");
        }
    }


    @Override
    public List<Long> queryLikeUserProfile(String name) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        if (!StringUtils.isEmpty(name)) {
            builder.and(qUserProfile.realName.like("%" + name + "%"));
        }
        Page<UserProfile> userProfiles = userProfileRepository.findAll(builder, new PageRequest(0, 1000000));
        List<Long> ids = new ArrayList<>();
        for (UserProfile userProfile : userProfiles) {
            ids.add(userProfile.getId());
        }
        return ids;
    }

    public List<Long> queryLikeUserId(String name) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        if (!StringUtils.isEmpty(name)) {
            builder.and(qUserProfile.realName.like("%" + name + "%"));
        }
        Page<UserProfile> userProfiles = userProfileRepository.findAll(builder, new PageRequest(0, 1000000));
        List<Long> ids = new ArrayList<>();
        for (UserProfile userProfile : userProfiles) {
            ids.add(userProfile.getUser().getId());
        }
        return ids;
    }
}
